<?php

namespace App\Api\Validate;


use App\Models\Goods;
use App\Models\GoodsStock;
use App\Models\RoomSendHis;
use Illuminate\Support\Facades\Validator;

class DeliveryValidate extends BaseValidate
{

    public function order($params)
    {
        $rules = [
            'goods_id' => 'required|not_in:0',
            'num' => 'required|not_in:0',
        ];

        $messages = [
            'goods_id.required'  => '请选择配送商品',
            'goods_id.not_in'    => '请选择配送商品',
            'num.required' => '请选择配送数量',
            'num.not_in'   => '请选择配送数量',
        ];
        $validator = Validator::make($params, $rules, $messages);
        $this->check($validator);
    }


    public function goodAndStockCheck($params)
    {
        $goods = Goods::where('id', $params['goods_id'])->first();
        if (!$goods || $goods->status != 1) {
            $this->return('商品不存在');
        }

        $goods_stock = $this->stock($params['goods_id'], $params['num']);

        if ($goods->day_per) {
            if ($params['num'] > $goods->day_per) {
                $this->return('每天限量' . $goods->day_per . '件');
            }
            // 今日已领取
            $receivedNum = RoomSendHis::receivedToday($params['goods_id'], $params['openid']);
            if (($params['num'] + $receivedNum) > $goods->day_per) {
                $this->return('每天限量' . $goods->day_per . '件，今日已领' . $receivedNum . '件');
            }
        }

        return [$goods, $goods_stock];
    }

    public function stock($goodId, $num)
    {
        $goods_stock = GoodsStock::where('goods_id', $goodId)->first();
        if (!$goods_stock) {
            $this->return('库存不足');
        }

        if ($num > $goods_stock->leave_num) {
            $this->return('库存不足');
        }
        return $goods_stock;
    }

    /**
     * 订单基础验证（适用单条记录验证）
     * @param $params
     * @return mixed
     * @throws \Exception
     */
    public function baseCheck($params)
    {
        if (!array_key_exists('id', $params) || !$params['id']) {
            $this->return('参数错误');
        }

        $record = RoomSendHis::where('id', $params['id'])->first();
        if (!$record) {
            $this->return('配送订单不存在');
        }

        if($record->status == 1) {
            $this->return('订单已完成');
        }

        if($record->status == 2) {
            $this->return('订单已取消');
        }
        return $record;
    }

}
